<template>
  <BasicModal
    :canFullscreen="false"
    @cancel="handleCancel"
    v-bind="$attrs"
    @register="registerModal"
    :title="title"
    width="50%"
  >
    <div class="container">
      <BasicForm @register="registerForm" />
    </div>
    <template #footer>
      <a-button @click="handleCancel">关闭</a-button>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup name="EditModal">
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { roleSchemas, field } from './roles.data';
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const title = ref('');
  const isEdit = ref(false);
  const editData = ref({});
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    editData.value = data;
    if (data.roleId) {
      title.value = '编辑';
    } else {
      title.value = '新增';
    }
    isEdit.value = data.isEdit;
    setFieldsValue(data);
  });

  import { BasicForm, useForm } from '/@/components/Form/index';
  const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
    labelWidth: 150,
    schemas: roleSchemas,
    showActionButtonGroup: false,
  });
  async function handleSubmit() {
    const values = await validate();
    const params = Object.assign({}, { ...editData.value, ...values });
    createMessage.success('操作成功');
    emit('success', { ...field, ...params }, isEdit.value);
    handleCancel();
  }
  function handleCancel() {
    resetFields();
    closeModal();
  }
</script>
<style lang="less" scoped></style>
